<template>
    <section class="account-box">
        <app-header></app-header>

        <figure>
            <img src="/static/img/account-header-bg3.jpg">
            <div class="head-box">
                <img :src="isNullImg(userHead)">
                <p><span @click="uploadHeadShow = true">修改头像</span></p>
            </div>
        </figure>
        <a-row class="main" :gutter="30">
            <a-col :span="4" class="NavMenu">
                <app-menu></app-menu>
            </a-col>
            <a-col :span="20" class="right-content">
                <router-view></router-view>
            </a-col>
        </a-row>

        <!--上传头像modal框-->
        <a-modal v-model="uploadHeadShow" title="上传头像" :footer="null" @cancel="uploadHeadModalCancel" class="uploadHead-modal">
            <p style="margin: 0 0 15px 0; text-align: left;"><i class="iconfont icon-wenjian"></i>支持 jpg、jpeg、png 格式文件，文件大小需小于 2M.</p>
            <a-upload
                    ref="uploadHead"
                    name="myFile"
                    listType="picture-card"
                    class="avatar-uploader"
                    :showUploadList="false"
                    action="https://www.hmoversea.com/api/v1/upload/photo"
                    :beforeUpload="beforeUpload"
                    @change="handleChange"
                    :supportServerRender="true">
                <img v-if="userHead" :src="userHead" alt="avatar" />
                <div v-else>
                    <a-icon :type="loading ? 'loading' : 'plus'" />
                    <div class="ant-upload-text">Upload</div>
                </div>
            </a-upload>

            <p v-show="false">{{getUserHeadPhoto}}</p>
        </a-modal>

        <!--返回顶部-->
        <BackTop :isShowHouseContrast="true"></BackTop>
    </section>
</template>

<script>
    import Header from '../../components/header.vue';//公共头部
    import Menu from '../account/leftMenu.vue'
    import BackTop from '../../components/BackTop.vue';//公共组件——返回顶部

    function getBase64 (img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    export default {
        data() {
            return {
                uploadHeadShow: false,//上传头像modal框是否显示
                userHead: '/static/img/upload-Head-notHead.jpg',
                loading: false,

            }
        },
        metaInfo () {
            return {
                title: '个人中心设置_华美优胜美国房地产投资公司',
                meta: [
                    { vmid: 'keywords', name: 'keywords', content: '个人中心设置_华美优胜美国房地产投资公司' },
                    { vmid: 'description', name: 'description', content: '个人中心设置_华美优胜美国房地产投资公司' },

                ],
            }
        },
        computed: {
            getUserHeadPhoto() {
                this.userHead = this.$store.getters.get_user.headPhoto;
                return this.$store.getters.get_user.headPhoto
            }
        },
        created() {
        },
        mounted() {
        },
        methods: {
            //上传文件之前的钩子，参数为上传的文件，若返回 false 则停止上传。
            //支持返回一个 Promise 对象，Promise 对象 reject 时则停止上传，resolve 时开始上传（ resolve 传入 File 或 Blob 对象则上传 resolve 传入对象）。注意：IE9 不支持该方法。
            beforeUpload (file) {
                // console.log(file)
                const isJPEG = file.type === 'image/jpeg';
                const isJPG = file.type === 'image/jpg';
                const isPNG = file.type === 'image/png';
                let isImageFormat = false;
                // console.log(isJPEG, isJPG, isPNG)
                if (!isJPEG && !isJPG && !isPNG) {
                    this.$notification['warning']({
                        message: '图片格式不正确！',
                        description: '请选择jpeg、jpg或png格式！'
                    });
                    isImageFormat = false;
                }else{
                    isImageFormat = true;
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$notification['warning']({
                        message: '图片大小超过限制',
                        description: '图片大小不能超过2M。'
                    });
                }
                // console.log(isImageFormat, isLt2M)
                return isImageFormat && isLt2M
            },
            // 上传文件改变时的状态
            handleChange (info) {
                // console.log(info)
                if (info.file.status === 'uploading') {
                    this.loading = true;
                    return
                }
                if (info.file.status === 'done') {
                    // Get this url from response in real world.
                    getBase64(info.file.originFileObj, (imageUrl) => {
                        this.userHead = imageUrl;
                        this.loading = false;
                        let imgUrl = info.file.response.data;
                        // console.log(imageUrl)
                        // console.log(imgUrl)

                        this.$post('/update/photo',{
                            photo: imgUrl
                        }).then(res => {
                            if (res.status == 0) {
                                this.uploadHeadShow = false;
                                this.$notification['success']({
                                    message: '头像设置成功！',
                                });
                                //更新个人中心的头像
                                this.userHead = imgUrl;
                                //更新公共头部和state里user登陆者信息的头像
                                this.$store.commit('set_user', {
                                    name: this.$store.getters.get_user.name,
                                    headPhoto: imgUrl,
                                });

                                //更新main.js里的全局守卫使用
                                localStorage.userHeadPhoto = imgUrl;
                            } else {
                                this.$notification['error']({
                                    message: res.msg,
                                });
                            }
                        });
                    })
                }
            },
            //上传头像modal框关闭时触发
            uploadHeadModalCancel(){
                this.uploadHeadShow = false;
            },

        },
        components: {
            'app-header': Header,
            'app-menu': Menu,
            BackTop,
        },

    }
</script>

<style lang="less" type="text/less">
    body {
        .account-box {
            > figure {
                width: 100%;
                > img {
                    width: 100%;
                    height: auto;
                }
                > div.head-box {
                    width: 100%;
                    height: 140px;
                    text-align: center;
                    > img {
                        width: 120px;
                        height: 120px;
                        border: 2px solid #fff;
                        border-radius: 50%;
                        outline: none;
                        margin: 0 auto;
                        margin-top: -60px;
                    }
                    > p {
                        color: #b5b5b5;
                        margin-top: 10px;
                        cursor: pointer;
                    }
                }
            }
            > .main {
                margin-left: 0 !important;
                margin-right: 0 !important;
                padding: 0 30px 30px 30px;
                .NavMenu {
                    > div {
                        background: #fff;
                    }
                }
                .right-content {
                    > section {
                        background: #fff;
                        padding: 20px;
                        min-height: 740px;
                    }
                }
            }
        }
        .uploadHead-modal{
            .ant-upload{
                img{
                    width: 100px;
                }
            }
        }
    }
</style>
